package p03_SingleLinkedList.quiz.q02_剑指offer24_单链表的反转;

//Definition for singly-linked list.
public class ListNode {
    int val;
    ListNode next;

    ListNode() {
    }

    ListNode(int val) {
        this.val = val;
    }

    ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }
}

class Solution {
    public ListNode reverseList(ListNode head) {
        if (head == null) {
            return head;
        }
        ListNode temp = head;
        int len = getLength(head);
        ListNode[] arr = new ListNode[len];
        int c = 0;
        while (temp != null) {
            arr[c] = temp;
            temp = temp.next;
            c++;
        }

        for (int i = arr.length - 1; i >= 1; i--) {
            arr[i].next = arr[i - 1];
        }
        arr[0].next = null;
        return arr[len - 1];
    }

    public static int getLength(ListNode head) {
        if (head == null) {
            return 0;
        }
        int len = 0;
        ListNode temp = head;
        while (temp != null) {
            temp = temp.next;
            len++;
        }
        return len;
    }

    public ListNode reverseList1(ListNode head) {
        if (head == null) {
            return head;
        }
        ListNode cur = head;
        ListNode pre = null;
        while (cur != null) {
            ListNode temp = cur.next;
            cur.next = pre;
            pre = cur;
            cur = temp;
        }
        return pre;
    }

}
